<template>
  <div>
    <!-- 条件筛选 -->
    <el-row :gutter="24">
      <el-col :span="24">
        <el-card shadow="always">
          <el-form :inline="true" :model="queryForm" ref="queryForm" class="demo-form-inline">
            <el-form-item label="商品名" prop="productName">
              <el-input v-model="queryForm.productName" placeholder="商品名"></el-input>
            </el-form-item>
            <el-form-item label="条码" prop="productCode">
              <el-input v-model="queryForm.productCode" placeholder="条码"></el-input>
            </el-form-item>
            <el-form-item label="商品分类" prop="productType">
              <el-cascader v-model="queryForm.productType" :props="{emitPath:false}"
                           :options="productTypes" :show-all-levels="false"></el-cascader>
            </el-form-item>
            <el-form-item label="销售渠道" prop="channel">
              <el-select v-model="queryForm.channel" placeholder="销售渠道">
                <el-option label="线下" value="0"></el-option>
                <el-option label="线上" value="1"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="售卖方式" prop="saleType">
              <el-select v-model="queryForm.saleType" placeholder="售卖方式">
                <el-option label="计件" value="0"></el-option>
                <el-option label="计重" value="1"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="发布时间" prop="publishTime">
              <el-date-picker
                v-model="queryForm.publishTime"
                type="daterange"
                value-format="yyyy-MM-ddTHH:mm:ss.000Z"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期">
              </el-date-picker>
            </el-form-item>
            <el-form-item>
              <el-button type="warning" @click="resetForm('queryForm')">重置</el-button>
              <el-button type="primary" @click="onSubmit">查询</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </el-col>
    </el-row>

    <br>

    <!-- 按钮操作 -->
    <el-row :gutter="24">
      <el-col :span="24">
        <el-card shadow="always" style="text-align: left">
          <el-button type="primary" size="small" @click="addOrUpdate('')">商品添加</el-button>
          <el-button type="success" size="small" @click="exportData">导出商品</el-button>
          <el-button type="success" size="small" @click="dialogFormVisible = true">商品导入</el-button>
          <el-button type="danger" size="small" @click="batchDel">批量删除</el-button>
        </el-card>
      </el-col>
    </el-row>

    <br>

    <!-- 数据列表 -->
    <el-row :gutter="24">
      <el-col :span="24">
        <el-card shadow="always">
          <el-table :data="tableData" border style="width: 100%" @selection-change="handleSelectionChange"
                    @sort-change = "sortChange">
            <el-table-column type="selection" width="50"></el-table-column>
            <el-table-column prop="productName" label="商品" width="320" sortable = "custom"></el-table-column>
            <el-table-column label="图片">
              <template slot-scope="scope">
                <el-image style="width: 78px; height: 58px" :src="'http://localhost:7000/admin/file/download?fileName='+scope.row.productImg">
                  <div slot="error" class="image-slot" v-if="scope.row.productImg == null">
                    <i class="el-icon-picture-outline"></i>
                  </div>
                </el-image>
              </template>
            </el-table-column>
            <el-table-column prop="productCode" label="条码"></el-table-column>
            <el-table-column prop="productType" label="分类"></el-table-column>
            <el-table-column prop="channel" label="渠道">
              <template slot-scope="scope">
                <span>{{ scope.row.channel === 0?'线下' :'线上'}}</span>
              </template>
            </el-table-column>
            <el-table-column prop="saleNum" label="销量" sortable = "custom"></el-table-column>
            <el-table-column prop="createTime" label="发布时间" sortable = "custom"></el-table-column>
            <el-table-column label="操作" width="130">
              <template slot-scope="scope">
                <el-button type="text" size="small" @click="handleClick(scope.row)">查看</el-button>
                <el-button type="text" size="small" @click="addOrUpdate(scope.row.id)">编辑</el-button>
                <el-button type="text" size="small" @click="delData(scope.row.id)">删除</el-button>
                <el-button type="text" size="small">规格设置</el-button>
                <el-button type="text" size="small">上架</el-button>
              </template>
            </el-table-column>
          </el-table>
          <div class="block" style="margin-top: 10px; text-align: right">
            <el-pagination
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
              :current-page="currentPage"
              :page-sizes="[10, 20, 30, 50]"
              :page-size="pageSize"
              layout="total, sizes, prev, pager, next, jumper"
              :total="dataCount">
            </el-pagination>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 商品导入 -->
    <el-dialog title="导入商品" :visible.sync="dialogFormVisible" :before-close = "closeProductImport">
      <el-form style="text-align: left">
        <el-form-item label="商品规格" :label-width="formLabelWidth">
          <template>
            <el-radio v-model="specification" label="1">
              无规格商品&nbsp;&nbsp;&nbsp;<a href="http://localhost:2000/product/download?fileName=商品导入模板.xlsx">模板下载</a>
            </el-radio><br>
            <el-radio v-model="specification" label="2">
              多规格商品&nbsp;&nbsp;&nbsp;<a href="http://localhost:2000/product/download?fileName=商品导入模板.xlsx">模板下载</a>
            </el-radio>
          </template>
        </el-form-item>
        <el-form-item label="导入数据" :label-width="formLabelWidth">
          <el-upload
            class="upload-demo"
            ref="upload"
            action="http://localhost:2000/product/import"
            :on-change = "fileChange"
            :on-success = "onSuccess"
            :file-list="fileList"
            :auto-upload="false" :limit = "3" :on-exceed = "onExceed">
            <el-button slot="trigger" size="small" type="primary">选取文件</el-button>
            <div slot="tip" class="el-upload__tip">只能上传xls/xlsx文件，且不超过1MB</div>
          </el-upload>
        </el-form-item>
      </el-form>
      <span v-if="exportResult">本次共导入{{ count }}条数据，成功{{ successCount }}条，失败{{ errorCount }}条
        <a href="#" v-if="errorCountShow">导出失败数据</a></span>
      <div slot="footer" class="dialog-footer">
        <el-button style="margin-left: 10px;" type="success" @click="submitUpload">开始导入</el-button>
      </div>
    </el-dialog>


  </div>
</template>

<script>
  import {get, post} from '@/api/http.js'

  export default {
    name: "productList",

    // 页面加载就执行
    mounted: function () {
      this.getListData();
      this.getProductType();
    },

    // 双向数据绑定
    data() {
      return {
        // 表单数据邦迪
        queryForm: {
          productName: '',
          productCode: '',
          productType: '',
          channel: '',
          saleType: '',
          publishTime: [],
          current: 0,
          size: 10,
          sortBy: '',
          sortOrder: ''
        },

        // 表格数据
        tableData: [],

        // 列表多选数据ID集合
        selectIds: [],

        // 分页参数
        currentPage: 1,
        pageSize: 10,
        dataCount: 0,

        // 导入弹框
        dialogFormVisible: false,
        formLabelWidth: '120px',
        specification: '',

        // 文件列表
        fileList: [],

        // 导入数据结果控制
        exportResult: false,
        count: 0,
        successCount: 0,
        errorCount: 0,
        errorCountShow: false,

        // 商品分类
        productTypes: []
      }
    },

    // 方法区
    methods: {
      // 获取商品分类数据
      getProductType(){
        post("/product/typeTree", '')
          .then(res => {
            this.productTypes = res.data;
          })
          .catch(err => {})
          .finally(() => {})
      },

      // 表格排序
      sortChange(column){
        this.queryForm.sortBy = column.prop;
        this.queryForm.sortOrder = column.order;
        this.getListData();
      },

      // 关闭商品导入对话框之前的回调
      closeProductImport(done){
        this.fileList = [];
        this.exportResult = false;
        this.errorCountShow = false;
        done();
      },

      // 文件改变时调用
      fileChange(file, fileList){
        this.fileList = fileList;
        console.info("===文件改变时调用===");
        let fileName = file.name;
        let suffix = fileName.substr(fileName.lastIndexOf("."), fileName.length);
        if(suffix === '.xlsx' || suffix === '.xls'){
        }else{
          this.$message({
            type: 'error',
            message: '文件格式错误，仅支持.xlsx/.xls'
          });
          // 移除不符合规格的文件
          let index = fileList.findIndex(fileItem => {
            return fileItem.uid === file.uid
          });
          fileList.splice(index, 1)
        }
      },
      // 超出文件选中个数
      onExceed(){
        this.$message({
          type: 'error',
          message: '最多支持上传3个文件'
        });
      },
      // 执行上传方法
      submitUpload() {
        if(this.fileList.length === 0){
          this.$message({
            type: 'error',
            message: '请至少选中一个文件进行导入'
          });
          return;
        }
        alert();
        this.$refs.upload.submit();
      },

      // 上传成功回调
      onSuccess(response, file, fileList){
        // 显示结果
        this.exportResult = true;
        this.count = response.data.count;
        this.successCount = response.data.successCount;
        this.errorCount = response.data.errorCount;
        if(this.errorCount > 0){
          this.errorCountShow = true;
        }
        this.$message({
          type: 'success',
          message: '导入完成'
        });
      },

      // 导出Excel
      exportData() {
        this.$axios({
          method: 'post',
          url: '/product/export',
          data: this.queryForm,
          responseType: 'blob'
        }).then(res => {
          // 可以从响应头截取文件名 decodeURI(data.headers['content-disposition']) ，也可以自行拼接
          let fileName = "商品列表.xlsx";
          // 将`blob`对象转化成一个可访问的`url`
          let url = window.URL.createObjectURL(new Blob([res.data]));
          let link = document.createElement('a');
          link.style.display = 'none';
          link.href = url;
          link.setAttribute('download', fileName);
          document.body.appendChild(link);
          link.click();
          document.body.removeChild(link);
          this.$message({
            type: 'success',
            message: '导出成功'
          });
        }).catch(err => {
          this.$message({
            type: 'error',
            message: '导出失败'
          });
        });
      },

      // 提交查询表单
      onSubmit() {
        this.getListData();
      },

      // 重置查询表单
      resetForm(formName) {
        this.$refs[formName].resetFields();
      },

      // 商品添加或修改
      addOrUpdate(id) {
        this.$store.commit("setProductId", id);
        this.$router.replace({name: "ProductEdit"})
      },

      // 表格数据多选,获取ID
      handleSelectionChange(val) {
        // val 传给的是数组，里面放的是选中当前行的所有数据
        // console.info(val);
        // 声明一个空数组，将val遍历获取每一行数据的ID，放入集合
        let idsArr = [];
        val.forEach(row => {
          idsArr.push(row.id)
        });
        // 赋值给全局变量
        this.selectIds = idsArr;
      },

      // 批量删除
      batchDel() {
        if (this.selectIds.length === 0) {
          this.$message({
            type: 'warning',
            message: '请至少选择一条数据'
          });
          return;
        }
        // 调用删除方法
        this.delData(this.selectIds.toString());
      },

      // 删除数据
      delData(id) {
        this.$confirm('此操作将永久删除该数据, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          let param = {ids: id};
          get('/product/del', param)
            .then(res => {
              this.$message({
                type: 'success',
                message: '删除成功'
              });
            })
            .catch(err => {
              this.$message({
                type: 'error',
                message: '删除失败'
              });
            }).finally(() => {
            this.getListData();
          })
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });
        });
      },

      // 分页组件参数变动
      handleSizeChange(val) {
        this.queryForm.size = val;
        this.getListData();
      },
      handleCurrentChange(val) {
        this.queryForm.current = val;

        this.getListData();
      },

      // 获取列表数据
      getListData() {
        post("/product/list", this.queryForm)
          .then(res => {
            this.tableData = res.data.records;
            this.dataCount = res.data.total;
            this.pageSize = res.data.size;
            this.currentPage = res.data.current;
          })
          .catch(err => {

          })
          .finally(() => {

          })
      }
    }
  }
</script>

<style scoped>

</style>
